package com.example.intermediateactivity;

import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;


import com.example.intermediateactivity.database.ShoppingCartDBHelper;
import com.example.intermediateactivity.entity.GoodsInfo;
import com.example.intermediateactivity.utils.FileUtil;
import com.example.intermediateactivity.utils.SharedUtil;

import java.io.File;
import java.util.ArrayList;

public class MyApplication extends Application {

    private static MyApplication instance;
    public int goodsCountInCart = 0;

    public static MyApplication getInstance() {
        if (instance == null) {
            instance = new MyApplication();
        }
        return instance;
    }

    public void initGoodsInfoTable() {

        // 通过共享参数文件中的first字段判断：时候第一次打开
        String sharedKey = "first";
        boolean isFirst = SharedUtil.getInstance(this)
                .readBoolean(sharedKey, true);


        // 外部存储的download文件夹路径
        String directory = this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                .toString() + File.separatorChar;

        Log.d("zhoutao", "is first: " + isFirst);

        if (isFirst) {
            // 第一次打开，把商品信息插入数据库

            // 模拟网络下载，从drawable中复制图片到外部存储的download文件夹中
            ArrayList<GoodsInfo> infoList = GoodsInfo.getDefaultList();
            for (GoodsInfo info : infoList) {
                // 通过drawable资源创建位图对象bitmap
                Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), info.pic);
                String path = directory + info.id + ".jpeg";
                // 保存图片到download目录
                FileUtil.saveImage(path, bitmap);
                // 回收位图对象
                bitmap.recycle();
                // 设置商品的图片路径
                info.picPath = path;

                // Log.d("zhoutao", "info: "+info);
            }

            // 打开数据库，插入默认的商品信息
            ShoppingCartDBHelper dbHelper = ShoppingCartDBHelper.getInstance(this);
            dbHelper.openWriteLink();
            // 插入商品信息
            dbHelper.insertGoodsInfos(infoList);
            dbHelper.closeLink();

            // 通过共享参数文件中的first字段设置为false：首次打开为否
            SharedUtil.getInstance(this).writeBoolean(sharedKey, false);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("zhoutao", "My Application.onCreate: ");
        initGoodsInfoTable();
    }
}
